#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <errno.h>


#define N 32
#define ERRLOG(errmsg) do{\
                                                            perror(errmsg);\
                                                            printf("file:%s,func:%s,line:%d\n",__FILE__,__func__,__LINE__);\
                                                            exit(-1);\
                                                            }while(0);



int main(int argc, char const *argv[])
{
    if(argc != 3){
        ERRLOG("argc is invalid");
    }

    int sockfd=-1;
    struct sockaddr_in servaddr;
    socklen_t addrlen=sizeof(servaddr);

    if((sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1){
        ERRLOG("socket error");
    }

    memset(&servaddr,0,addrlen);
    servaddr.sin_family=AF_INET;
    servaddr.sin_addr.s_addr=inet_addr(argv[1]);
    servaddr.sin_port=htons(atoi(argv[2]));

    char buf[N]={0};

    while(1){
        fgets(buf,N,stdin);
        buf[strlen(buf)-1]='\0';

        if(strcmp(buf,"QUIT")==0){
            exit(0);
        }

        if(sendto(sockfd,buf,N,0,(struct sockaddr*)&servaddr,addrlen)==-1){
            ERRLOG("sendto error");
        }

        memset(buf,0,N);

        if(recvfrom(sockfd,buf,N,0,NULL,NULL)==-1){
            ERRLOG("recvfrom error");
        }
        printf("buf=%s\n",buf);
    }
    return 0;
}
